﻿function BoggleTraversalViewModel(data, grid) {
    var _this = this;
    var opts = data || {};
    var visitedCellsMapping = {
        'visitedCells': {
            create: function(options) {
                return new BoggleCellViewModel(options.data);
            }
        }
    };
    ko.mapping.fromJS(data, visitedCellsMapping, this);
    
    this.word = ko.observable(opts.word);
    
    var highlightRender = function (instance, td, row, col, prop, value, cellProperties) {
        Handsontable.TextCell.renderer.apply(this, arguments);
        $(td).addClass('highlight');
    };
    
    var normalRenderer = function (instance, td, row, col, prop, value, cellProperties) {
        Handsontable.TextCell.renderer.apply(this, arguments);
        $(td).removeClass('highlight');
    };
    
    this.highlightGrid = function() {
        var cellRenderer = {
            cells: function (row, col, prop) {
                var highlight;
                ko.utils.arrayForEach(_this.visitedCells(), function (visitedCell) {
                    if(visitedCell.row() === row && visitedCell.column() === col) {
                        highlight = true;
                    }
                });
                if (highlight) {
                    return { type: { renderer: highlightRender } };
                }else {
                    return { type: { renderer: normalRenderer } };
                }
            }
        };
        grid.handsontable('updateSettings', cellRenderer);
        grid.handsontable('loadData', grid.handsontable('getData'));
    };
    
    this.unhighlightGrid = function () {
        var cellRenderer = {
            cells: function (row, col, prop) {
                return { type: { renderer: normalRenderer } };
            }
        };
        grid.handsontable('updateSettings', cellRenderer);
        grid.handsontable('loadData', grid.handsontable('getData'));
    };
}